#include <54func.h>
int main(int argc,char *argv[])
{
    // ./5_aqiang 1.pipe 2.pipe
    ARGS_CHECK(argc,3);
    int fdr = open(argv[1],O_RDONLY);
    ERROR_CHECK(fdr,-1,"open read");
    int fdw = open(argv[2],O_WRONLY);
    ERROR_CHECK(fdw,-1,"open write");
    printf("aqiang is connected!\n");
    char buf[4096] = {0};
    fd_set rdset;//创建一个文件描述符集合
    while(1)
    {
        FD_ZERO(&rdset);//创建一个监听集合
        //设置好监听集合：把可能会发生阻塞的行为，增加监听集合,这里有两个读文件会产生阻塞行为
        FD_SET(fdr,&rdset);
        FD_SET(STDIN_FILENO,&rdset);
        //监听轮询
        select(fdr+1,&rdset,NULL,NULL,NULL);
        //分情况对监听到的行为进行处理
        if(FD_ISSET(fdr,&rdset))//如果监听到了fdr行为
        {
            //从啊珍那个管道里读消息
            memset(buf,0,sizeof(buf));
            //若是对方断开连接，那么管道的写端也断开，那么我这一边的读端会返回0
            ssize_t sret = read(fdr,buf,sizeof(buf));
            if(sret == 0){
                printf("aqiang is out\n");
                break;
            }
            printf("azhen:%s\n",buf);
        }else if(FD_ISSET(STDIN_FILENO,&rdset))//阿强把用户输入的消息发送给阿珍
        {
            memset(buf,0,sizeof(buf));
            ssize_t sret =read(STDIN_FILENO,buf,sizeof(buf));
            if(sret == 0){
                write(fdw,"see you !\n",9);
                break;
            }
            write(fdw,buf,strlen(buf));
        }
        //啊强发消息给阿珍
        //memset(buf,0,sizeof(buf));
        //read(STDIN_FILENO,buf,sizeof(buf));
        //write(fdw,buf,strlen(buf));
        //啊强收到啊珍的消息
        // memset(buf,0,sizeof(buf));
        //read(fdr,buf,sizeof(buf));
        //printf("azhen： %s\n",buf);
    }
    //close(fdr);
    //close(fdw);
    return 0;
}
